﻿using Ewell.Interface.Common.Model.Common;
using Ewell.Interface.Common.Model.GateWay;
using Ewell.Interface.Common.Model.JsonConverter;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;

namespace Ewell.Interface.Common.Utils
{
    public class HttpHelper
    {
        public static GateWayResult postBasic(string url, string param)
        {
            string result = postBasic(url, param, Encoding.UTF8);
            return JsonConvert.DeserializeObject<GateWayResult>(result);
        }
        public static GateWayResult<T> postBasic<T>(string url, string param)
        {
            string result=postBasic(url, param, Encoding.UTF8);
            return JsonConvert.DeserializeObject<GateWayResult<T>>(result);
        }

        public static GateWayResult<R> postBasic<T,R>(string url, T param)
        {
            return postBasic<R>(url,JsonConvert.SerializeObject(param,new JsonDateTimeConverter()));
        }

        public static string postBasic(string url, string param, Encoding encode)
        {
            try
            {
                LogHelper.Debug($"ThreadId-【{Thread.CurrentThread.ManagedThreadId}】请求地址:{url}");
                LogHelper.Debug($"ThreadId-【{Thread.CurrentThread.ManagedThreadId}】请求参数:{param}");
                HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
                req.Timeout = 500000;

                req.Method = "POST";
                req.ContentType = "application/json";
                #region 添加Post 参数
                byte[] data = encode.GetBytes(param.ToString());
                req.ContentLength = data.Length;

                Stream outstream = req.GetRequestStream();
                outstream.Write(data, 0, data.Length);
                outstream.Close();
                #endregion
                //获取响应内容  
                HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
                Stream stream = resp.GetResponseStream();
                string content = string.Empty;
                using (StreamReader reader = new StreamReader(stream, encode))
                {
                    content = reader.ReadToEnd();
                    LogHelper.Debug($"ThreadId-【{Thread.CurrentThread.ManagedThreadId}】请求返回:{content}");
                }

                return content;
            }
            catch (Exception ex)
            {
                throw new SpeedException("GATEWAY","请求服务器出错！请检查网络!"+ex.Message);
            }
        }
    }
}
